package com.csust.automaticteach.demo.zhipu;

import ai.z.openapi.ZhipuAiClient;
import ai.z.openapi.service.model.*;
import ai.z.openapi.core.Constants;
import java.util.Arrays;

public class StreamingChat {
    public static void main(String[] args) {
        ZhipuAiClient client = ZhipuAiClient.builder()
            .apiKey("YOUR_API_KEY")
            .build();
        
        // 创建流式聊天请求
        ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
            .model(Constants.ModelChatGLM4_5)
            .messages(Arrays.asList(
                ChatMessage.builder()
                    .role(ChatMessageRole.USER.value())
                    .content("写一首关于春天的诗")
                    .build()
            ))
            .stream(true)
            .build();
        
        // 处理流式响应
        ChatCompletionResponse response = client.chat().createChatCompletion(request);
        
        if (response.isSuccess() && response.getFlowable() != null) {
            response.getFlowable().subscribe(
                data -> {
                    // 处理流式数据块
                    if (data.getChoices() != null && !data.getChoices().isEmpty()) {
                        String content = data.getChoices().get(0).getDelta().getContent();
                        if (content != null) {
                            System.out.print(content);
                        }
                    }
                },
                error -> System.err.println("\n流式错误: " + error.getMessage()),
                () -> System.out.println("\n流式完成")
            );
        }
    }
}